package per.hx.bs.service.impl;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import per.hx.bs.base.entity.EmailVO;
import per.hx.bs.config.EmailAddress;
import per.hx.bs.entity.SysEmailDO;
import per.hx.bs.service.IEmailService;
import per.hx.bs.service.ISysEmailService;

import java.util.Arrays;

/**
 * @author HuXing
 * @date 2018/4/26  11:38
 */
@Component
public class EmailServiceImpl implements IEmailService {


    private final EmailAddress emailAddress;
    /**
     * 邮件发送
     */
    private final JavaMailSender mailSender;

    private final
    ISysEmailService emailService;


    @Autowired
    public EmailServiceImpl(EmailAddress emailAddress, JavaMailSender mailSender, ISysEmailService emailService) {
        this.emailAddress = emailAddress;
        this.mailSender = mailSender;
        this.emailService = emailService;
    }


    @Override
    public void send(EmailVO email) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(emailAddress.getAddr());
        message.setTo(email.getEmail());
        message.setSubject(email.getSubject());
        message.setText(email.getContent());
        SysEmailDO sysEmailDO = new SysEmailDO();
        try {
            sysEmailDO.setEmail(Arrays.toString(email.getEmail()));
            sysEmailDO.setSubject(email.getSubject());
            sysEmailDO.setContent(email.getContent());
            sysEmailDO.setTemplate(email.getTemplate());
            sysEmailDO.setParams(JSON.toJSONString(email.getKvMap()));
            mailSender.send(message);
        } catch (Exception e) {
            e.printStackTrace();
            sysEmailDO.setRemark(e.getMessage());
            try {
                emailService.insertEmail(sysEmailDO);
            } catch (Exception e1) {
                e.printStackTrace();
            }
        }
        try {
            emailService.insertEmail(sysEmailDO);
        } catch (Exception ee) {
            ee.printStackTrace();
        }
    }

    @Override
    public void sendHtml(EmailVO email) {

    }

    @Override
    public void sendThymeleaf(EmailVO email) {

    }
}
